package com.jxs.android.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class SysUpdateHolder {

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
	public static String UPDATE_VERSIONG_FILE = FileHloder.ROOT + "/mms_mobile_" + sdf.format(new Date()) + ".apk";

	public static File getFileFromServer(String path, ProgressDialog pd, String fileName) throws Exception {
		// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);

			InputStream is = conn.getInputStream();
			File file = new File(Environment.getExternalStorageDirectory(), fileName);
			if (conn.getContentLength() != -1) {
				pd.setMax(conn.getContentLength());
			} else {
				pd.setMax((int) file.length());
			}

			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
				pd.setProgress(total);// 获取当前下载量
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		} else {
			return null;
		}
	}

	/**
	 * @Des 弹出对话框通知用户更新程序
	 * @1. 创建alertDialog的builder.
	 * @2. 要给builder设置属性, 对话框的内容,样式,按钮
	 * @3. 通过builder 创建一个对话框
	 * @4. 对话框show()出来
	 * @Author jiangxs(jxs)
	 * @Date 2011-11-1 下午02:45:11
	 * @param context
	 * @param downloadMessage
	 * @param json
	 * @param okBtnTextram
	 *            cancel
	 * @throws JSONException
	 */
	private static AlertDialog downLoadAlertDialog = null;

	public static void showUpdataDialog(final Activity context, final String downloadMessage, String title, final String url, final UpdateCancelListern updateCancelListern) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		// 设置Dialog的标题
		builder.setTitle(title);
		// 设置Dialog的icon
		// builder.setIcon(R.drawable.icon);
		// 设置Dialog的提示信息
		builder.setMessage(downloadMessage);
		builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface paramDialogInterface, int paramInt) {
				downLoadFile(context, downloadMessage, url, UPDATE_VERSIONG_FILE);
			}

		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface paramDialogInterface, int paramInt) {
				downLoadAlertDialog.dismiss();
				updateCancelListern.cancel();
			}
		});
		downLoadAlertDialog = builder.create();
		downLoadAlertDialog.show();
	}

	static public interface UpdateCancelListern {
		public void cancel();
	}

	/**
	 * @Des 从服务器中下载
	 * @Author jiangxs(jxs)
	 * @Date 2011-11-1 下午02:44:17
	 * @param context
	 * @param downloadMessage
	 * @param url
	 */
	public static void downLoadFile(final Context context, String downloadMessage, final String url, final String fileName) {
		final ProgressDialog pd; // 进度条对话框
		pd = new ProgressDialog(context);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage(downloadMessage);
		pd.show();
		new Thread() {
			@Override
			public void run() {
				try {
					File file = getFileFromServer(url, pd, fileName);
					sleep(3000);
					installApk(context, file);
					pd.dismiss(); // 结束掉进度条对话框
				} catch (Exception e) {
					Log.e("SysUpdateHolder", e + "", e);
				}
			}
		}.start();
	}

	/**
	 * @Des 当点确定按钮时从服务器上下载 新的apk 然后安装
	 * @Author jiangxs(jxs)
	 * @Date 2011-11-1 下午02:44:50
	 * @param context
	 * @param file
	 */
	protected static void installApk(Context context, File file) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		context.startActivity(intent);
	}
}
